package com.sls.nzdapplication.ui.fragment;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bin.david.form.core.SmartTable;
import com.bin.david.form.data.column.Column;
import com.bin.david.form.data.format.draw.ImageResDrawFormat;
import com.bin.david.form.data.style.FontStyle;
import com.bin.david.form.data.table.TableData;
import com.bin.david.form.utils.DensityUtils;
import com.hmy.popwindow.PopItemAction;
import com.hmy.popwindow.PopWindow;
import com.sls.nzdapplication.R;
import com.sls.nzdapplication.db.utils.MeterBoxUtil;
import com.sls.nzdapplication.db.utils.MeterUtil;
import com.sls.nzdapplication.db.utils.UserDataUtil;
import com.sls.nzdapplication.model.DyManagementUser;
import com.sls.nzdapplication.model.Meter;
import com.sls.nzdapplication.model.MeterBox;
import com.sls.nzdapplication.model.User;
import com.sls.nzdapplication.util.DeviceUtils;


import java.util.ArrayList;
import java.util.List;

/**
 * 这个类是一个低压用户管理的Fragment，主要用于展示低压用户的信息，包括用户的序号、表号、用户、地址和状态等信息。
 * 其中状态是通过电表的条形码查询电表所在的表箱，如果表箱所在的区域和当前区域相同，则状态为“ok”，
 * 否则为“question”，如果查询不到电表，则状态为“null”。在展示用户信息的同时，还可以通过点击每一行的信息，弹出一个窗口，展示该用户的详细信息。
 * */
public class DyManagementUserFragment extends Fragment {

    private UserDataUtil userDataUtil;

    private LinearLayout dataView;

    private List<User> userList;

    private String lineId;

    PopWindow  popupWindow;

    private MeterUtil meterUtil;

    private MeterBoxUtil meterBoxUtil;

    ProgressDialog pd2;

    SmartTable<DyManagementUser> table;




    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dy_user_manage_layout, container, false);

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        lineId = getArguments().getString("areaId");
        table = view.findViewById(R.id.table);
        table.getConfig().setShowXSequence(false);
        table.getConfig().setShowYSequence(false);
        table.getConfig().setShowTableTitle(false);
        table.getConfig().setColumnTitleStyle (new FontStyle(30, getResources().getColor(R.color.colorPrimaryDark)));
        table.getConfig().setMinTableWidth(getActivity().getWindowManager().getDefaultDisplay().getWidth());
        initData();

    }

    private void initData(){
        userDataUtil = new UserDataUtil(getContext());
        meterBoxUtil = new MeterBoxUtil(getContext());
        meterUtil = new MeterUtil(getContext());
        userList = userDataUtil.queryUserByAreaId(lineId);

        showData(userList);
    }

    @Override
    public void onResume() {
        super.onResume();
//        initData();
    }

    private void showData(List<User> titleData){
        table.setTableData(null);
        List<DyManagementUser> dyManagementUserList = new ArrayList<>();
        for (int i = 0; i < titleData.size(); i++) {
            final User user = titleData.get(i);
            DyManagementUser dyManagementUser = new DyManagementUser();
            dyManagementUser.setXh(String.valueOf(i+1));

            dyManagementUser.setBh(user.getUserBoxNumber());

            dyManagementUser.setUser(user.getUsername());

            dyManagementUser.setAddress(user.getAddress());

            Meter meter = meterUtil.queryMeterByMeterCode(user.getBarCode());
            if(meter==null){
               dyManagementUser.setZt("null");
            }
            else{
                MeterBox meterBox = meterBoxUtil.listOneMeterBox(meter.getBoxId());
                if(meterBox.getAreaId().equals(lineId)){
                    dyManagementUser.setZt("ok");
                }else{
                    dyManagementUser.setZt("question");
                }
            }
            dyManagementUserList.add(dyManagementUser);
        }
//        table.setData(dyManagementUserList);
//        if(table.getTableData()!=null){
//            table.getTableData().setOnRowClickListener(new TableData.OnRowClickListener<DyManagementUser>() {
//                @Override
//                public void onClick(Column column, DyManagementUser dyManagementUser, int col, int row) {
//                    openInfo(titleData.get(row));
//                }
//            });
//        }

        final Column<String> xhColumn = new Column<>("序号", "xh");
        final Column<String> bhColumn = new Column<>("表号", "bh");
        final Column<String> userColumn = new Column<>("用户", "user");
        final Column<String> addressColumn = new Column<>("地址", "address");
        int size = DensityUtils.dp2px(getContext(),15); //指定图标大小
        Column<String> checkColumn = new Column<>("状态", "zt",new ImageResDrawFormat<String>(size,size) {
            @Override
            protected Context getContext() {
                return DyManagementUserFragment.this.getContext();
            }

            @Override
            protected int getResourceID(String isCheck, String value, int position) {
                if(isCheck.equals("null")){
                    return R.drawable.x;
                }
                if(isCheck.equals("ok")){
                    return R.drawable.y;
                }
                if(isCheck.equals("question")){
                    return R.drawable.wh;
                }
                return 0;
            }
        });

            if(dyManagementUserList.size()>0){
                table.setVisibility(View.VISIBLE);
                TableData<DyManagementUser> tableData = new TableData<>("低压用户",dyManagementUserList,xhColumn,bhColumn,userColumn,addressColumn,checkColumn);
                table.setTableData(tableData);
                table.getTableData().setOnRowClickListener(new TableData.OnRowClickListener<DyManagementUser>() {
                    @Override
                    public void onClick(Column column, DyManagementUser dyManagementUser, int col, int row) {
                        openInfo(titleData.get(row));
                    }
                });
            }else{
                table.setVisibility(View.GONE);
            }

    }

    private void openInfo(User user){
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,600);
        List<String> info = new ArrayList<>();
        ListView listView = new ListView(getContext());
        listView.setLayoutParams(layoutParams);
        info.add("电表局编号："+user.getElectricityMeterOfficeNumber());
        info.add("用户编号："+user.getUserCode());
        info.add("用户名称："+user.getUsername());
        info.add("用电地址："+user.getAddress());
        info.add("电能表条形码："+user.getBarCode());
        info.add("表箱号："+user.getUserBoxNumber());
        info.add("修改后表箱号："+user.getModifyBoxCode());
        info.add("采集序号："+user.getSerialNumber());
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getContext(), android.R.layout.simple_list_item_1, info);
        listView.setAdapter(adapter);
        popupWindow= new PopWindow.Builder((Activity) getContext())
                .setStyle(PopWindow.PopWindowStyle.PopAlert)
                .setMessage("用户信息查看")
                .addContentView(listView)
                .setIsShowCircleBackground(false)
                .addItemAction(new PopItemAction("关闭", PopItemAction.PopItemStyle.Warning))
                .setPopWindowMarginsF(DeviceUtils.dip2px4View(getContext(),30), DeviceUtils.dip2px4View(getContext(),200), DeviceUtils.dip2px4View(getContext(),30), DeviceUtils.dip2px4View(getContext(),0))
                .show();

    }

    class UpdateTask extends AsyncTask<Void, Integer, Boolean> {

        @Override
        protected void onPreExecute() {
            pd2 = new ProgressDialog(getActivity());
            pd2.setTitle("数据初始化");
            pd2.setIcon(R.mipmap.ic_launcher_round);
            pd2.setMessage("数据正在初始化，请等待...");
            pd2.setCancelable(false);
            pd2.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pd2.show();

        }

        @Override
        protected Boolean doInBackground(Void... params) {

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showData(userList);

                }
            });
            return true;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {

        }

        @Override
        protected void onPostExecute(Boolean result) {
            pd2.hide();

        }
    }
}
